import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { motion } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import EditProfileModal from '../components/EditProfileModal';
import ChangePasswordModal from '../components/ChangePasswordModal';
import { colors, spacing, typography } from '../styles/variables';
import { Card, Title, Paragraph, Button, Flex, Grid } from '../styles/components';

const ProfileHeader = styled.div`
  text-align: center;
  padding: ${spacing.xl} 0;
  margin-bottom: ${spacing.xl};
`;

const ProfileCard = styled(Card)`
  display: flex;
  align-items: center;
  gap: ${spacing.xl};
  margin-bottom: ${spacing.xl};
`;

const Avatar = styled.div`
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: ${colors.gradientGold};
  display: flex;
  align-items: center;
  justify-content: center;
  color: ${colors.background};
  font-size: 2.5rem;
  font-weight: bold;
`;

const UserInfo = styled.div`
  flex: 1;
`;

const StatGrid = styled(Grid)`
  margin: ${spacing.xxl} 0;
`;

const StatCard = styled(Card)`
  text-align: center;
  padding: ${spacing.lg};
`;

const StatValue = styled.div`
  font-size: ${typography.fontSize['3xl']};
  font-weight: ${typography.fontWeight.bold};
  color: ${colors.primary};
  margin: ${spacing.md} 0;
`;

const StatLabel = styled.div`
  color: ${colors.textSecondary};
`;

const HistoryItem = styled(Card)`
  margin-bottom: ${spacing.md};
  padding: ${spacing.md};
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const HistoryTitle = styled.h4`
  color: ${colors.textPrimary};
  margin-bottom: ${spacing.sm};
`;

const HistoryDate = styled.div`
  color: ${colors.textSecondary};
  font-size: ${typography.fontSize.sm};
`;

const VIPBadge = styled.span`
  background: ${colors.gradientGold};
  color: ${colors.background};
  padding: ${spacing.sm} ${spacing.md};
  border-radius: ${spacing.lg};
  font-size: ${typography.fontSize.sm};
  font-weight: ${typography.fontWeight.bold};
`;

const tabs = [
  { id: 'overview', label: '概览' },
  { id: 'history', label: '历史记录' },
  { id: 'favorites', label: '收藏' },
  { id: 'settings', label: '设置' }
];

// 模拟历史记录数据
const historyItems = [
  { id: 1, title: '八字测算', date: '2023-10-15', type: '测算' },
  { id: 2, title: '塔罗占卜 - 爱情运势', date: '2023-10-10', type: '占卜' },
  { id: 3, title: '梦见飞翔解梦', date: '2023-10-05', type: '解梦' },
  { id: 4, title: '10分钟冥想练习', date: '2023-10-01', type: '心灵驿站' }
];

function Profile() {
  const [activeTab, setActiveTab] = useState('overview');
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isChangePasswordModalOpen, setIsChangePasswordModalOpen] = useState(false);
  const { user, logout } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    // 如果用户未登录，重定向到登录页面
    if (!user) {
      navigate('/login');
    }
  }, [user, navigate]);

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  // 处理编辑资料成功
  const handleEditSuccess = () => {
    // 可以在这里添加一些成功提示或其他逻辑
    console.log('资料更新成功');
  };

  const handleChangePasswordSuccess = () => {
    // 可以在这里添加一些成功提示或其他逻辑
    console.log('密码修改成功');
  };

  // 获取用户名首字母用于头像显示
  const getInitials = (name) => {
    if (!name) return 'U';
    return name.charAt(0).toUpperCase();
  };

  // 格式化注册日期
  const formatRegistrationDate = (date) => {
    if (!date) return '未知';
    return new Date(date).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  return (
    <>
      <ProfileHeader>
        <Title>个人中心</Title>
        <Paragraph center>查看您的个人信息和使用记录</Paragraph>
      </ProfileHeader>

      <ProfileCard>
        <Avatar>{getInitials(user?.username || user?.email)}</Avatar>
        <UserInfo>
          <Flex align="center" gap={spacing.md} style={{ marginBottom: spacing.sm }}>
            <Title size="md" style={{ margin: 0 }}>
              {user?.username || user?.email || '用户名'}
            </Title>
            {user?.isVip && <VIPBadge>VIP会员</VIPBadge>}
          </Flex>
          <Paragraph secondary>
            注册于 {formatRegistrationDate(user?.createdAt)}
          </Paragraph>
          <Flex gap={spacing.lg} style={{ marginTop: spacing.md }}>
            <Button variant="outline" size="sm" onClick={() => setIsEditModalOpen(true)}>编辑资料</Button>
            <Button variant="primary" size="sm">升级VIP</Button>
          </Flex>
        </UserInfo>
      </ProfileCard>

      <Card>
        <Flex gap={spacing.lg} wrap>
          {tabs.map((tab) => (
            <Button
              key={tab.id}
              variant={activeTab === tab.id ? 'primary' : 'outline'}
              onClick={() => setActiveTab(tab.id)}
            >
              {tab.label}
            </Button>
          ))}
        </Flex>
      </Card>

      {activeTab === 'overview' && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.5 }}
        >
          <StatGrid columns={4} gap={spacing.md}>
            <StatCard>
              <StatValue>24</StatValue>
              <StatLabel>总测算次数</StatLabel>
            </StatCard>
            <StatCard>
              <StatValue>12</StatValue>
              <StatLabel>占卜记录</StatLabel>
            </StatCard>
            <StatCard>
              <StatValue>8</StatValue>
              <StatLabel>解梦次数</StatLabel>
            </StatCard>
            <StatCard>
              <StatValue>15</StatValue>
              <StatLabel>心灵练习</StatLabel>
            </StatCard>
          </StatGrid>

          <Card>
            <Title size="md">最近活动</Title>
            {historyItems.slice(0, 3).map((item) => (
              <HistoryItem key={item.id}>
                <div>
                  <HistoryTitle>{item.title}</HistoryTitle>
                  <HistoryDate>{item.date}</HistoryDate>
                </div>
                <Button variant="outline" size="sm">查看详情</Button>
              </HistoryItem>
            ))}
            <Flex justify="center" style={{ marginTop: spacing.lg }}>
              <Button variant="outline" onClick={() => setActiveTab('history')}>
                查看全部记录
              </Button>
            </Flex>
          </Card>
        </motion.div>
      )}

      {activeTab === 'history' && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.5 }}
        >
          <Card>
            <Title size="md">使用历史</Title>
            {historyItems.map((item) => (
              <HistoryItem key={item.id}>
                <div>
                  <HistoryTitle>{item.title}</HistoryTitle>
                  <HistoryDate>{item.date} · {item.type}</HistoryDate>
                </div>
                <Button variant="outline" size="sm">重新查看</Button>
              </HistoryItem>
            ))}
          </Card>
        </motion.div>
      )}

      {activeTab === 'favorites' && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.5 }}
        >
          <Card>
            <Title size="md">我的收藏</Title>
            <Paragraph center>您还没有收藏任何内容</Paragraph>
            <Flex justify="center" style={{ marginTop: spacing.lg }}>
              <Button variant="primary">去探索</Button>
            </Flex>
          </Card>
        </motion.div>
      )}

      {activeTab === 'settings' && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.5 }}
        >
          <Card>
            <Title size="md">账户设置</Title>
            <Grid columns={2} gap={spacing.lg}>
              <Button 
                variant="outline" 
                style={{ justifyContent: 'center' }}
                onClick={() => setIsChangePasswordModalOpen(true)}
              >
                修改密码
              </Button>
              <Button variant="outline" style={{ justifyContent: 'center' }}>
                绑定手机号
              </Button>
              <Button variant="outline" style={{ justifyContent: 'center' }}>
                隐私设置
              </Button>
              <Button variant="outline" style={{ justifyContent: 'center' }}>
                通知设置
              </Button>
            </Grid>
          </Card>
          
          <Card>
            <Title size="md">其他</Title>
            <Grid columns={2} gap={spacing.lg}>
              <Button variant="outline" style={{ justifyContent: 'center' }}>
                意见反馈
              </Button>
              <Button variant="outline" style={{ justifyContent: 'center' }}>
                关于我们
              </Button>
              <Button variant="outline" style={{ justifyContent: 'center' }}>
                清除缓存
              </Button>
              <Button 
              variant="outline" 
              style={{ justifyContent: 'center', color: colors.error }}
              onClick={handleLogout}
            >
              退出登录
            </Button>
            </Grid>
          </Card>
        </motion.div>
      )}
      <EditProfileModal 
        isOpen={isEditModalOpen}
        onClose={() => setIsEditModalOpen(false)}
        onSuccess={handleEditSuccess}
      />
      
      <ChangePasswordModal 
        isOpen={isChangePasswordModalOpen}
        onClose={() => setIsChangePasswordModalOpen(false)}
        onSuccess={handleChangePasswordSuccess}
      />
    </>
  );
}

export default Profile;